<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="注意！只允许为第三级分类设置相关参数！" type="warning" show-icon :closable="false"></el-alert>
      <el-row>
        <el-col>
          选择商品分类：
          <el-cascader
            v-model="selectCate"
            :options="cateOptions"
            :props="{ expandTrigger: 'hover', value: 'cat_id', label: 'cat_name', children: 'children' }"
            @change="handleChange"
          ></el-cascader>
          <el-tabs v-model="activeTabName" @tab-click="handleTabClick">
            <el-tab-pane label="动态参数" name="many">
              <template>
                <el-button
                  type="primary"
                  size="small"
                  :disabled="isBtnDisabled"
                  @click="addAttrDialog"
                >添加参数</el-button>
                <el-table :data="attrList" border stripe>
                  <el-table-column type="expand">
                    <template slot-scope="scoped">
                      <el-tag
                        v-for="(item, i) in scoped.row.attr_vals"
                        :key="i"
                        closable
                        @close="tagClose(i, scoped.row)"
                      >{{item}}</el-tag>
                      <el-input
                        class="input-new-tag"
                        v-if="scoped.row.inputVisible"
                        v-model="scoped.row.inputValue"
                        ref="saveTagInput"
                        size="small"
                        @keyup.enter.native="handleInputConfirm(scoped.row)"
                        @blur="handleInputConfirm(scoped.row)"
                      ></el-input>
                      <el-button
                        v-else
                        class="button-new-tag"
                        size="small"
                        @click="showInput(scoped.row)"
                      >+ New Tag</el-button>
                    </template>
                  </el-table-column>
                  <el-table-column label="#" type="index" align="center"></el-table-column>
                  <el-table-column label="参数名称" prop="attr_name" align="center"></el-table-column>
                  <el-table-column label="操作" align="center">
                    <template slot-scope="scoped">
                      <el-button
                        type="primary"
                        size="small"
                        round
                        @click="editAttrDialog(scoped.row)"
                      >编辑</el-button>
                      <el-button type="danger" size="small" round @click="deleteAttr(scoped.row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </el-tab-pane>
            <el-tab-pane label="静态参数" name="only">
              <template>
                <template>
                  <el-button
                    type="primary"
                    size="small"
                    :disabled="isBtnDisabled"
                    @click="addAttrDialog"
                  >添加参数</el-button>
                  <el-table :data="attrList" border stripe>
                    <el-table-column type="expand">
                      <template slot-scope="scoped">
                        <el-tag
                          v-for="(item, i) in scoped.row.attr_vals"
                          :key="i"
                          closable
                          @close="tagClose(i, scoped.row)"
                        >{{item}}</el-tag>
                        <el-input
                          class="input-new-tag"
                          v-if="scoped.row.inputVisible"
                          v-model="scoped.row.inputValue"
                          ref="saveTagInput"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scoped.row)"
                          @blur="handleInputConfirm(scoped.row)"
                        ></el-input>
                        <el-button
                          v-else
                          class="button-new-tag"
                          size="small"
                          @click="showInput(scoped.row)"
                        >+ New Tag</el-button>
                      </template>
                    </el-table-column>
                    <el-table-column label="#" type="index" align="center"></el-table-column>
                    <el-table-column label="参数名称" prop="attr_name" align="center"></el-table-column>
                    <el-table-column label="操作" align="center">
                      <template slot-scope="scoped">
                        <el-button
                          type="primary"
                          size="small"
                          round
                          @click="editAttrDialog(scoped.row)"
                        >编辑</el-button>
                        <el-button
                          type="danger"
                          size="small"
                          round
                          @click="deleteAttr(scoped.row)"
                        >删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </template>
              </template>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-card>
    <!-- 添加分类参数对话框 -->
    <el-dialog
      :title="'添加'+dialogText"
      :visible.sync="addDialogVisiable"
      width="50%"
      @close="addAttrDialogClose"
    >
      <el-form
        :model="addAttrForm"
        :rules="addAttrFormRules"
        ref="addAttrFormRef"
        label-width="70px"
      >
        <el-form-item label="参数名" prop="attr_name">
          <el-input v-model="addAttrForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisiable = false">取 消</el-button>
        <el-button type="primary" @click="addCateAttr">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑分类参数对话框 -->
    <el-dialog :title="'编辑'+dialogText" :visible.sync="editDialogVisiable" width="50%">
      <el-form
        :model="editAttrForm"
        :rules="addAttrFormRules"
        ref="editAttrFormRef"
        label-width="70px"
      >
        <el-form-item label="参数名" prop="attr_name">
          <el-input v-model="editAttrForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisiable = false">取 消</el-button>
        <el-button type="primary" @click="editCateAttr">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selectCate: [],
      cateOptions: [],
      activeTabName: "many",
      attrList: [],
      //添加分类参数标题
      addDialogTitle: "",
      //添加分类参数弹窗 显示
      addDialogVisiable: false,
      //添加分类参数表单
      addAttrForm: {
        attr_name: "",
        attr_vals: "",
      },
      //添加分类参数表单验证规则
      addAttrFormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", tigger: "blur" },
        ],
      },
      //编辑分类参数对话框 显示
      editDialogVisiable: false,
      editAttrForm: {
        attr_name: "",
        attr_vals: "",
        attr_id: "",
        attr_sel: "",
        cat_id: "",
      },
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    //获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200)
        return this.$message.error("获取商品分类列表失败！");
      this.cateOptions = res.data;
    },
    //选择分类事件
    handleChange(value) {
      console.log(this.selectCate);
      if (value.length != 3) {
        this.selectCate = [];
        this.attrList = [];
        return;
      }
      this.getAttr();
    },
    //tab点击事件
    handleTabClick(value) {
      if (this.selectCate.length == 0)
        return this.$message.info("请先选择商品分类！");
      this.getAttr();
    },
    //获取参数列表
    async getAttr() {
      const { data: res } = await this.$http.get(
        `categories/${this.selectCate[2]}/attributes`,
        {
          params: { sel: this.activeTabName },
        }
      );
      if (res.meta.status !== 200)
        return this.$message.error("获取分类参数失败！");
      res.data.forEach((item, i) => {
        item.attr_vals == ""
          ? (item.attr_vals = [])
          : (item.attr_vals = item.attr_vals.split(","));
        item.inputValue = "";
        item.inputVisible = false;
      });
      this.attrList = res.data;
    },
    //添加参数对话框
    addAttrDialog() {
      this.addDialogVisiable = true;
    },
    //添加分类参数
    async addCateAttr() {
      const { data: res } = await this.$http.post(
        `categories/${this.selectCate[2]}/attributes`,
        {
          attr_name: this.addAttrForm.attr_name,
          attr_sel: this.activeTabName,
        }
      );
      if (res.meta.status !== 201)
        return this.$message.error("添加分类参数失败！");
      this.addDialogVisiable = false;
      this.$message.success("添加分类参数成功！");
      this.addAttrForm.attr_name = "";
      this.getAttr();
    },
    //添加分类参数对话框 关闭事件
    addAttrDialogClose() {
      this.addAttrForm.attr_name = "";
    },
    //编辑分类参数对话框
    editAttrDialog(attrinfo) {
      console.log(attrinfo);
      this.editDialogVisiable = true;
      this.editAttrForm.cat_id = attrinfo.cat_id;
      this.editAttrForm.attr_name = attrinfo.attr_name;
      this.editAttrForm.attr_sel = attrinfo.attr_sel;
      this.editAttrForm.attr_id = attrinfo.attr_id;
    },
    //编辑分类参数
    async editCateAttr() {
      const { data: res } = await this.$http.put(
        `categories/${this.editAttrForm.cat_id}/attributes/${this.editAttrForm.attr_id}`,
        this.editAttrForm
      );
      if (res.meta.status !== 200)
        return this.$message.error("更新分类参数失败！");
      this.editDialogVisiable = false;
      this.$message.success("更新分类参数成功！");
      this.getAttr();
    },
    //删除分类参数警告
    async deleteAttr(Attrinfo) {
      var result = await this.$confirm(
        "此操作将永久删除该参数, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((res) => res);
      if (result == "cancel") return this.$message.info("用户取消了删除操作");
      const { data: res } = await this.$http.delete(
        `categories/${Attrinfo.cat_id}/attributes/${Attrinfo.attr_id}`
      );
      if (res.meta.status !== 200) return this.$message.error("删除参数失败！");
      this.$message.success("已删除参数！");
      this.getAttr();
    },
    //tag按钮点击事件,显示input
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //tag input回车确认事件 或 鼠标离开事件
    async handleInputConfirm(row) {
      row.inputVisible = false;
      //处理前后空白字符
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      //将参数值写入后台
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      const { data: res } = await this.$http.put(
        `categories/${row.cat_id}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(","),
        }
      );
      if (res.meta.status !== 200) return this.$message.error("添加参数错误");
      this.$message.success("修改参数成功！");
    },
    async tagClose(i, row) {
      console.log(i);
      row.attr_vals.splice(i, 1);
      const { data: res } = await this.$http.put(
        `categories/${row.cat_id}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(","),
        }
      );
      if (res.meta.status !== 200) return this.$message.error("修改参数错误");
      this.$message.success("修改参数成功！");
    },
  },
  computed: {
    isBtnDisabled() {
      if (this.selectCate.length !== 3) return true;
      return false;
    },
    dialogText() {
      return this.activeTabName == "many" ? "动态参数" : "静态参数";
    },
  },
};
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 15px;
}
.el-row {
  margin-top: 15px;
}
.el-table {
  margin-top: 15px;
}
.el-tag {
  margin-left: 10px;
  margin-bottom: 10px;
}
.input-new-tag {
  width: 100px;
}
</style>